<?php
namespace app\api\controller\Content;

use app\api\controller\Common;
use app\api\Logic\CommonLogic;
use app\api\model\CommentModel;
use app\api\model\QuestionModel;
use app\api\model\SimpleCategoryModel;
use think\Request;

/**
 * 内容中心
 * 知识问答
 */
class Question extends Common{
    protected $noNeedLogin = ['*'];


    /** 
     * 获取问题分类
     */
    public function getSimpleCategory(){
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //验证数据
            $param = $this->contentVerifyData($param);
            $list = SimpleCategoryModel::where('type',1)->field('id,name')->select();
            return $this->success('查询成功',$list);
        }
        $this->error('请求错误');
    }

    /**
     * 发布问题
     */
    public function release(){
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //验证数据
            $param = $this->contentVerifyData($param);
            if(empty($param['type_id'])){
                $this->error('未传入分类id');
            }
            if(empty($param['title'])){
                $this->error('未传入标题');
            }
            if(empty($param['content'])){
                $this->error('未传入问题内容');
            }
            $model = new QuestionModel;
            $all = Request::instance()->post(false);
            $content = $all['content'];
            $model->save([
                'shop_id'=>$param['shop_id'],
                'type_id'=>$param['type_id'],
                'title'=>$param['title'],
                'content'=>$content,
                'type'=>1,
                'relation_id'=>$param['teacher_id'],
                'is_question'=>1
            ]);
            return $this->success('发布成功');
        }
        $this->error('请求错误');
    }

    /**
     * 问题列表
     */
    public function list(){
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //验证数据
            $param = $this->contentVerifyData($param);
            if(empty($param['type'])){
                $this->error('未传入类型');
            }
            $where = [
                'status' => 1,
                'deletetime' => null
            ];
            $order = '';
            $page = $param['page'];
            $limit = $param['page_size'];
            if($param['type'] == 1 || $param['type'] == 2){
                //最新提问，最热提问
                if($param['type'] == 1){
                    $order = 'id desc';
                }else{
                    $order = 'views desc';
                }
                $list = QuestionModel::where($where)
                ->where(function($query){
                    $query->where('shop_id', 0)->where('power', 'like', '%2%');
                })->whereOr(function($query){
                    $query->where('shop_id', '>',0)->where('is_question',1);
                })
                ->order($order)
                ->limit(($page-1)*$limit,$limit)
                ->field('id,title,content,views,createtime')
                ->select();
                
            }else{
                //3我的提问
                $where['is_question'] = 1;
                $where['shop_id'] = $param['shop_id'];
                $where['relation_id'] = $param['teacher_id'];
                $order = 'id desc';
                $list = QuestionModel::where($where)
                ->order($order)
                ->limit(($page-1)*$limit,$limit)
                ->field('id,title,content,views,createtime')
                ->select();
            }
            
            foreach($list as $k=>$v){
                $list[$k]['comment_num'] = CommentModel::where(['style'=>'Question','relation_id'=>$v['id']])->count();
            }
                
            return $this->success('查询成功',$list);
        }
        $this->error('请求错误');
    }

    /**
     * 删除问题
     */
    public function del(){
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //验证数据
            $param = $this->contentVerifyData($param);
            if(empty($param['id'])){
                $this->error('未传入删除id');
            }
            $res = QuestionModel::where([
                    'id'=>$param['id'],
                    'shop_id'=>$param['shop_id'],
                    'relation_id'=>$param['teacher_id']
                ])->update(['deletetime'=>time()]);
            if($res){
                return $this->success('删除成功');
            }
            $this->error('删除失败');
        }
        $this->error('请求错误');
    }

    /**
     * 回答问题
     */
    public function reply(){
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //验证数据
            $param = $this->contentVerifyData($param);
            if(empty($param['id'])){
                $this->error('未传入提问id');
            }
            if(empty($param['content'])){
                $this->error('未传入问题内容');
            }
            $all = Request::instance()->post(false);
            $content = $all['content'];
            $model = new CommentModel;
            $model->save([
                'shop_id'=>$param['shop_id'],
                'style' => 'Question',
                'relation_id' => $param['id'],
                'reply_type' => 1,
                'content'=>$content,
                'reply_id'=>$param['teacher_id'],
                'audio'=>$param['audio'] ?? ''
            ]);
            return $this->success('回复成功');
        }
        $this->error('请求错误');
    }

    /**
     * 是否有未读消息
     */
    public function msgRead(){
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //验证数据
            $param = $this->contentVerifyData($param);
            $questionId = QuestionModel::where([
                        'status' => 1,
                        'deletetime' => null,
                        'is_question' => 1,
                        'shop_id' => $param['shop_id'],
                        'relation_id' => $param['teacher_id']
                    ])->column('id');
            $count = CommentModel::where([
                        'style' => 'Question',
                        'is_read' => 0
                    ])
                    ->whereIn('relation_id',$questionId)
                    ->count();
            if($count > 0){
                //有未读消息
                return $this->success('查询成功',['is_read'=>1]);
            }else{
                return $this->success('查询成功',['is_read'=>0]);
            }
        }
        $this->error('请求错误');
    }

    /**
     * 消息列表
     */
    public function msgList(){
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //验证数据
            $param = $this->contentVerifyData($param);
            $questionId = QuestionModel::where([
                        'status' => 1,
                        'deletetime' => null,
                        'is_question' => 1,
                        'shop_id' => $param['shop_id'],
                        'relation_id' => $param['teacher_id']
                    ])->column('id');
            $page = $param['page'];
            $limit = $param['page_size'];
            $list = CommentModel::alias('a')
                ->join('question q','a.relation_id = q.id','left')
                ->join('manystore m','a.reply_id = m.id','left')
                ->where(['a.style' => 'Question'])
                ->whereIn('a.relation_id',$questionId)
                ->order('a.id','desc')
                ->limit(($page-1)*$limit,$limit)
                ->field('a.id,a.is_read,a.createtime,q.title,m.username,a.relation_id')
                ->select();
            return $this->success('查询成功',$list);
  
        }
        $this->error('请求错误');
    }

    /**
     * 消息改为已读
     */
    public function readNotice(){
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //验证数据
            $param = $this->contentVerifyData($param);
            if(empty($param['id'])){
                $this->error('未传入消息id');
            }
            $res = CommentModel::where('id',$param['id'])->update(['is_read'=>1]);
            if($res !== false){
                return $this->success('操作成功');
            }
            return $this->success('操作失败');
  
        }
        $this->error('请求错误');
    }

    /**
     * 问答详情
     */
    public function info(){
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //验证数据
            $param = $this->contentVerifyData($param);
            if(empty($param['id'])){
                $this->error('未传入提问id');
            }
            $data = QuestionModel::alias('a')
                ->where('a.id',$param['id'])
                ->join('simple_category s','a.type_id = s.id','left')
                ->field('a.id,a.title,a.content,a.createtime,a.views,a.relation_id,a.type,s.name')
                ->find();
            if($data){
                $commonLogic = new CommonLogic();
                //获取作者头像信息
                $user_info = $commonLogic->getUserInfo($data['type'],$data['relation_id']);
                $data['nickname'] = $user_info['nickname'];
                $data['avatar'] = $user_info['avatar'];
                // 浏览数+1
                $data->setInc('views');
                $commentCount = CommentModel::where([
                    'style' => 'Question',
                    'relation_id' => $param['id'],
                    'deletetime' => null,
                ])->count();
                $data['comment_count'] = $commentCount;
            }
            return $this->success('查询成功',$data);
        }
        $this->error('请求错误');
    }

    /**
     * 评论详情
     */
    public function commentInfo(){
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //验证数据
            $param = $this->contentVerifyData($param);
            if(empty($param['id'])){
                $this->error('未传入提问id');
            }
            
            $page = $param['page'];
            $limit = $param['page_size'];
            $where = [
                'a.style' => 'Question',
                'a.relation_id' => $param['id'],
                'a.deletetime' => null,
            ];
            $data = model('CommentModel')
            ->alias('a')
            ->where($where)
            ->limit(($page-1)*$limit,$limit)
            ->order('a.createtime desc')
            ->field('a.id,a.shop_id,a.reply_type,a.reply_id,a.content,a.createtime,a.audio')
            ->select();

            if($data){
                foreach ($data as &$v) {
                    $commonLogic = new CommonLogic();
                    $user_info = $commonLogic->getUserInfo($v['reply_type'],$v['reply_id']);
                    $v['nickname'] = $user_info['nickname'];
                    $v['avatar'] = $user_info['avatar'];
                }
            }
            $this->success('查询成功',$data);
        }
        $this->error('请求错误');
    }

    /**
     * 搜索
     */
    public function search(){
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //验证数据
            $param = $this->contentVerifyData($param);
            if(empty($param['search_name'])){
                $this->error('未传入关键字');
            }
            $where = [
                'status' => 1,
                'deletetime' => null
            ];
            if($param['shop_id'] == 0){
                $where['power'] = ["like",'%2%'];
            }else{
                $where['is_question'] = 1;
            }
            $where['title'] = ["like",'%'.$param['search_name'].'%'];
            $order = 'id desc';
            
            $page = $param['page'];
            $limit = $param['page_size'];
            $list = QuestionModel::where($where)
                ->order($order)
                ->limit(($page-1)*$limit,$limit)
                ->field('id,title,content,views,createtime')
                ->select();
            foreach($list as $k=>$v){
                $list[$k]['comment_num'] = CommentModel::where(['style'=>'Question','relation_id'=>$v['id']])->count();
            }
                
            return $this->success('查询成功',$list);
        }
        $this->error('请求错误');
    }
}